package com.ruoyi.project.check.service.impl;

import com.ruoyi.common.core.lang.UUID;
import com.ruoyi.project.check.domain.HisCheckList;
import com.ruoyi.project.check.mapper.HisCheckListMapper;
import com.ruoyi.project.check.service.HisUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Service
public class HisUploadServiceImpl implements HisUploadService {
    @Autowired
    private HisCheckListMapper hisCheckListMapper;
    // 保存文件的文件夹名称。
    private final String dir = "D:/uploadFiles";
    @Override
    public int uploadResult(HisCheckList hisCheckList) {
        int list = hisCheckListMapper.setResult(hisCheckList.getRrcresult(), hisCheckList.getRrcpicture(), hisCheckList.getRrcstatus(),hisCheckList.getRrcid());
        return list;
    }

    @Override
    public byte[] getImage(String imageName) {
        String name= imageName.substring(imageName.lastIndexOf("/")+1);
        System.out.println(name);

        File file= new File(new File(dir),name);

        FileInputStream inputStream=null;
        byte[] datas=null;

        try {
            inputStream = new FileInputStream(file);

            datas=new byte[inputStream.available()];
            inputStream.read(datas,0,datas.length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            datas=null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("datas"+datas);

        return datas;
    }


    /**
     *保存到本地。
     * @param
     * @return
     */
    @Override
    @Transactional
    public String uploadFile(MultipartFile file) {
        String randomFileName = "";

        // 获取文件的原始名称。
        String originalFileName = file.getOriginalFilename();

        String extName="";

        if (originalFileName.indexOf(".") >= 0) {
            extName = originalFileName.substring(originalFileName.lastIndexOf("."));
        }

        randomFileName=UUID.randomUUID().toString()+extName;

        File dir = new File(this.dir);
        if (!dir.exists()){
            dir.mkdir();
        }

        File file1 = new File(dir,randomFileName);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
            return "失败";
        }


        String fDir=dir+"/"+randomFileName;
        System.out.println(fDir);

        return fDir;
    }


}
